package pers.hl.module_login

import com.blankj.utilcode.util.LogUtils
import com.tencent.mmkv.MMKV
import pers.hl.common.base.BaseViewModel
import pers.hl.common.base.SingleLiveEvent
import pers.hl.lib_global.common.Const
import pers.hl.lib_global.common.MD5Utils
import pers.hl.lib_global.common.MMKVHelper
import pers.hl.lib_global.model.bean.User

class LoginViewModel : BaseViewModel<LoginModel>() {

    val loginUserData = SingleLiveEvent<User>()

    fun login(account: String, password: String): SingleLiveEvent<User> {
        launchOnIO {
            val response = mModel.login(account, MD5Utils.string2MD5(password))
            val user = response.data
            user.password = password
            saveUserInfo(user)
            LogUtils.d("token:${user.token}")
            LogUtils.d("user:${user}")
            loginUserData.postValue(user)
        }
        return loginUserData
    }

    private fun saveUserInfo(user: User) {
        MMKV.defaultMMKV()?.apply {
            encode(Const.KEY.KEY_TOKEN, user.token)
        }
        MMKVHelper.saveUser(user)
    }

    fun register(account: String, password: String): SingleLiveEvent<User> {
        return createSimpleEvent {
            val response = mModel.register(account, password)
            response.data
        }
    }
}